﻿using System;
using System.Threading;
using TYBase;

namespace TYRTUBase
{
    public class Device_Switch : DeviceBase
    {
        public Device_Switch(string equipId, string equipName) : base(EnumEquipType.Switch, equipId, equipName)
        {
            SetPara(new ScanerPara
            {
                baudRate = 19200,
                dataBits = 8,
                parity = System.IO.Ports.Parity.None,
                stopBits = System.IO.Ports.StopBits.One,
            });
        }

        //public override void Init(int com, int baudRate = 19200)
        //{
        //    base.Init(com, new ScanerPara() { baudRate = baudRate, parity = System.IO.Ports.Parity.None, dataBits = 8, stopBits = System.IO.Ports.StopBits.One });
        //}

        public bool SwitchTo(int index)
        {
            if (IsXModerMode)
            {
                return true;
            }
            if (!CheckComOK())
                return false;
            byte[] byteSend = new byte[] { 0xAA, 0xBB, 0xCC, (byte)index };
            rtu.ClearInBuff();
            rtu.Write(byteSend);

            DateTime dtStart = DateTime.Now;
            byte[] dataReadAll = null;
            int repeat = 0;
            while (true)
            {
                Thread.Sleep(10);
                if (IsRun == false)
                    return false;
                if (DateTime.Now - dtStart < TimeSpan.FromMilliseconds(ReadOutTime))
                {
                    rtu.Read(out byte[] dataTmp);
                    if (dataTmp != null && dataTmp.Length > 0)
                    {
                        dataReadAll = dataReadAll.Append(dataTmp);
                        if (dataReadAll.Indexof(byteSend) >= 0)
                        {
                            Log.I($"switch receive :{dataReadAll.AsHexString()}");
                            return true;
                        }
                    }
                }
                else
                {
                    repeat++;
                    dtStart = DateTime.Now;
                    if (repeat >= repeatTime)
                    {
                        Log.I($"com :切换板 超时;total{dataReadAll.AsHexString()}");
                        return false;
                    }
                    else
                    {
                        rtu.Write(byteSend);
                    }
                }
            }
        }

        public void SendSwitchTo(int index)
        {
            if (!CheckComOK())
                return;
            byte[] byteSend = new byte[] { 0xAA, 0xBB, 0xCC, (byte)index };
            rtu.Write(byteSend);
            LastSendData = byteSend;
        }
    }
}